<?php
/**
 * 文件缓存类 - JBlog
 * 
 * @copyright (c) 2008-2010 JBlog (www.lisijie.org)
 * @author lisijie <lisijie86@gmail.com>
 * @version $Id: class_cache.php 551 2010-07-22 09:35:52Z lisijie86 $
*/

class Cache {
	
	var $expire;
	var $prefix; //缓存文件名前缀
	var $path;	 //缓存文件存放路径
	
	function Cache ($options = array()) {
		$this->__construct($options);
	}
	
	function __construct($options = array()) {
		$this->expire = isset($options['expire']) ? $options['expire'] : -1;
		$this->prefix = isset($options['prefix']) ? $options['prefix'] : '';
		$this->path = DATA_ROOT;
		if ( $options['dir'] ) {
			$this->path .= $options['dir'].DS;
			if ( !is_dir($this->path) ) {
				make_dir($this->path);
			}
		}		
	}
	
	//获取缓存文件路径
	function filename($name) {
		$name = $this->prefix.$name.'.php';
		return $this->path.$name;
	}
	
	//写入缓存
	function set($name, $value, $expire = '') {
		$name = $this->filename($name);
		if ( '' === $expire ) {
			$expire = $this->expire;
		}
		$value = serialize($value);
		if ( function_exists('gzcompress') ) {
			$value = gzcompress($value, 3);
		}
		$value = "<?php\n//".sprintf('%010d', $expire).$value."\n?>";
		$result = file_put_contents($name, $value);
		if ( $result ) {
			clearstatcache();
			return true;
		} else {
			return false;
		}
	}
	
	//读取缓存
	function get($name) {
		$name = $this->filename($name);
		if ( !is_file($name) ) return false;
		$data = file_get_contents($name);
		if ( false !== $data ) {
			$expire = substr($data, 8, 10);
			if ( $expire != -1 && NOW - filemtime($name) > $expire ) {
				unlink($name);
				return false;
			}
			$data = substr($data, 18, -3);
			if ( function_exists('gzcompress') ) {
				$data = gzuncompress($data);
			}
			$data = unserialize($data);
			return $data;
		}
		return false;
	}
	
	//删除缓存
	function del($name) {
		$name = $this->filename($name);
		return unlink($name);
	}
	
	//清空缓存
	function clear() {
		remove_dir($this->path);
	}
}
?>